
#include "gameboard.h"
#include "chessboard.h"
#include <QMouseEvent>
#include <QMessageBox>
#include <QDebug>
#include <QLabel>

const int edge = 20;
const int squre = 35;
const int ball = 32;

GameBoard::GameBoard(QWidget* parent)
{
    _board = new ChessBoard;
    background = new QLabel(this);
    background->setPixmap(QPixmap(":/images/board.png"));
    background->move(0,0);
    background->show();
    latestPane[0] = new QLabel(this);
    latestPane[1] = new QLabel(this);
    latestPane[0]->setPixmap(QPixmap(":/images/latestblack.png"));
    latestPane[1]->setPixmap(QPixmap(":/images/latestwhite.png"));
    //setupUi(this);
    setMinimumSize(534,534);
    restart();
}

void GameBoard::mouseReleaseEvent(QMouseEvent* e)
{
    int x = e->pos().x() - edge + squre / 2;
    int y = e->pos().y() - edge + squre / 2;
    if (addPane(x/squre, y/squre) == false)
        return;
    _board->getBestPlace(x, y);
    addPane(x, y);
}


void GameBoard::restart(bool humenFirst)
{
    turn = 1;
    latestPane[0]->hide();
    latestPane[1]->hide();
    _board->cleanUp();
    for (Map::iterator it = _maps.begin(); it != _maps.end(); it ++)
        delete it->second;
    
    _maps.clear();
    if (humenFirst) return;

    // 电脑先下子
    int x, y;
    _board->getBestPlace(x, y);
    addPane(x, y);
}


bool GameBoard::addPane(int x, int y)
{
    static const char* pics[2] = {
        ":/images/black.png",
        ":/images/white.png"
    };
    static const char* name[2] = {"black", "white"};
    
    if (_board->saveChess(x, y) == false)
        return false;
    
    // 计算轮到哪个棋子了
    turn = (turn + 1) % 2;
    
    // 显示图标
    QPixmap pic(pics[turn]);
    QLabel* one = new QLabel(this);
    one->setPixmap(pic);
    int x0 = x * squre + edge - ball/2;
    int y0 = y * squre + edge - ball/2;
    latestPane[turn]->move(x0, y0);
    latestPane[turn]->show();
    one->move(x0, y0);
    one->show();
    // 记录起来
    ChessPane* pane = _board->lastPane;
    _maps.insert(Map::value_type(pane, one));
    qDebug() << QString("%1 at (%2,%3) => (%4,%5)").arg(name[turn]).arg(x).arg(y).arg(x0).arg(y0);
    if (_board->scanBoard()){
        QMessageBox::information(this, "Win!", name[turn]);
        return false;
    }
    return true;
}


void GameBoard::undo()
{
    Map::iterator it;
    it = _maps.find(_board->lastPane);
    if (it != _maps.end()){
        delete (it->second);
        _maps.erase(it);
    }
    
    it = _maps.find(_board->lastPane2);
    if (it != _maps.end()){
        delete (it->second);
        _maps.erase(it);
    }
    _board->undo();
    _board->undo();
}

//#include "gameboard.moc"
